<template>
    <div class="shop-container">
        <el-card class="shop-card">
            <template #header>
                <div class="card-header">
                    <h2>商品列表</h2>
                    <el-button v-if="isAdmin()" type="primary" @click="handleAdd"
                        >新增商品</el-button
                    >
                </div>
            </template>

            <!-- 搜索区域 -->
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 商品列表 -->
            <div class="goods-grid">
                <el-card
                    v-for="item in goodsList"
                    :key="item.id"
                    class="goods-item"
                    :body-style="{ padding: '0px' }"
                >
                    <img :src="item.image" class="goods-image" />
                    <div class="goods-info">
                        <h3 class="goods-title">{{ item.name }}</h3>
                        <p class="goods-price">¥ {{ item.price }} 元/斤</p>
                        <p class="goods-desc">{{ item.description }}</p>
                        <div class="goods-actions">
                            <el-button type="primary" link @click="handleView(item)"
                                >查看详情</el-button
                            >
                            <template v-if="isAdmin()">
                                <el-button type="primary" link @click="handleEdit(item)"
                                    >编辑</el-button
                                >
                                <el-button type="danger" link @click="handleDelete(item)"
                                    >删除</el-button
                                >
                            </template>
                        </div>
                    </div>
                </el-card>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[12, 24, 36, 48]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 商品表单对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '新增商品' : '编辑商品'"
            width="500px"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
                label-position="left"
            >
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number
                        v-model="form.price"
                        :min="0"
                        :precision="2"
                        :step="10"
                        placeholder="请输入商品价格"
                    />
                </el-form-item>
                <el-form-item label="商品图片" prop="image">
                    <el-input v-model="form.image" placeholder="请输入图片URL" />
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input
                        v-model="form.description"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入商品描述"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 商品详情对话框 -->
        <el-dialog v-model="detailVisible" title="商品详情" width="600px">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="商品ID">{{ currentGoods.id }}</el-descriptions-item>
                <el-descriptions-item label="商品名称">{{
                    currentGoods.name
                }}</el-descriptions-item>
                <el-descriptions-item label="商品价格"
                    >¥{{ currentGoods.price }}</el-descriptions-item
                >
                <el-descriptions-item label="商品状态">
                    <el-tag :type="currentGoods.statue === 1 ? 'success' : 'danger'">
                        {{ currentGoods.statue === 1 ? '在售' : '下架' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="商品图片" :span="2">
                    <img :src="currentGoods.image" class="detail-image" />
                </el-descriptions-item>
                <el-descriptions-item label="商品描述" :span="2">
                    {{ currentGoods.description }}
                </el-descriptions-item>
                <el-descriptions-item label="购买数量" :span="2">
                    <el-input-number
                        v-model="buyNum"
                        :min="1"
                        :max="999"
                        :step="1"
                        @change="handleNumChange"
                    />
                </el-descriptions-item>
                <el-descriptions-item label="总价" :span="2">
                    <span class="total-price">¥{{ totalPrice }}</span>
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailVisible = false">关闭</el-button>
                    <el-button
                        v-if="currentGoods.statue === 1"
                        type="primary"
                        @click="handleBuy"
                        :loading="buyLoading"
                        :disabled="
                            !userStore.isLoggedIn() || userStore.userInfo.balance < totalPrice
                        "
                    >
                        购买
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    listCommodityByPage,
    addCommodity,
    updateCommodity,
    deleteCommodity
} from '@/api/commodity'
import { useUserStore } from '@/stores/user'
import { isAdmin } from '@/utils/auth'
import { addOrder } from '@/api/order'

const userStore = useUserStore()

// 搜索表单
const searchForm = ref({
    name: '',
    minPrice: null,
    maxPrice: null
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 商品列表
const goodsList = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const detailVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const currentGoods = ref({})

// 表单数据
const form = ref({
    name: '',
    price: 0,
    image: '',
    description: ''
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    image: [{ required: true, message: '请输入商品图片URL', trigger: 'blur' }],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' },
        { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
    ]
}

// 用户信息
const buyLoading = ref(false)

// 购买相关
const buyNum = ref(1)
const totalPrice = ref(0)

// 获取商品列表
const fetchGoodsList = async () => {
    loading.value = true
    try {
        const res = await listCommodityByPage({
            current: currentPage.value,
            pageSize: pageSize.value,
            name: searchForm.value.name,
            price:
                searchForm.value.minPrice || searchForm.value.maxPrice
                    ? {
                          min: searchForm.value.minPrice,
                          max: searchForm.value.maxPrice
                      }
                    : undefined
        })
        if (res.code === 0) {
            goodsList.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message || '获取商品列表失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '获取商品列表失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchGoodsList()
}

// 重置搜索
const resetSearch = () => {
    searchForm.value = {
        name: '',
        minPrice: null,
        maxPrice: null
    }
    handleSearch()
}

// 新增商品
const handleAdd = () => {
    dialogType.value = 'add'
    form.value = {
        name: '',
        price: 0,
        image: '',
        description: ''
    }
    dialogVisible.value = true
}

// 编辑商品
const handleEdit = row => {
    dialogType.value = 'edit'
    form.value = {
        id: row.id,
        name: row.name,
        price: row.price,
        image: row.image,
        description: row.description
    }
    dialogVisible.value = true
}

// 删除商品
const handleDelete = row => {
    ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteCommodity({ id: row.id })
            if (res.code === 0) {
                ElMessage.success('删除成功')
                fetchGoodsList()
            } else {
                ElMessage.error(res.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error(error.message || '删除失败')
        }
    })
}

// 处理数量变化
const handleNumChange = value => {
    totalPrice.value = (value * currentGoods.value.price).toFixed(2)
}

// 查看商品详情
const handleView = row => {
    currentGoods.value = row
    buyNum.value = 1
    totalPrice.value = row.price
    detailVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        const api = dialogType.value === 'add' ? addCommodity : updateCommodity
        const res = await api(form.value)

        if (res.code === 0) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
            dialogVisible.value = false
            fetchGoodsList()
        } else {
            ElMessage.error(res.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'))
        }
    } catch (error) {
        ElMessage.error(error.message || '表单验证失败')
    } finally {
        submitLoading.value = false
    }
}

// 分页相关方法
const handleSizeChange = val => {
    pageSize.value = val
    fetchGoodsList()
}

const handleCurrentChange = val => {
    currentPage.value = val
    fetchGoodsList()
}

// 购买商品
const handleBuy = () => {
    if (!userStore.isLoggedIn()) {
        ElMessage.warning('请先登录')
        return
    }
    console.log(
        userStore.userInfo.balance,
        totalPrice.value,
        userStore.userInfo.balance < totalPrice.value
    )
    if (Number(userStore.userInfo.balance) < Number(totalPrice.value)) {
        ElMessage.warning('余额不足')
        return
    }

    ElMessageBox.confirm(
        `确定要购买商品"${currentGoods.value.name}"吗？\n数量：${buyNum.value}\n单价：¥${currentGoods.value.price}\n总价：¥${totalPrice.value}\n当前余额：¥${userStore.userInfo.balance}`,
        '确认购买',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        buyLoading.value = true
        try {
            const res = await addOrder({
                name: currentGoods.value.name,
                payerid: userStore.userInfo.id,
                payeeid: '1931545438350131202',
                price: currentGoods.value.price,
                num: buyNum.value
            })
            if (res.code === 0) {
                ElMessage.success('购买成功')
                detailVisible.value = false
                // 刷新用户信息和商品列表
                await userStore.fetchUserInfo()
                fetchGoodsList()
            } else {
                ElMessage.error(res.message || '购买失败')
            }
        } catch (error) {
            ElMessage.error(error.message || '购买失败')
        } finally {
            buyLoading.value = false
        }
    })
}

onMounted(async () => {
    await userStore.fetchUserInfo()
    fetchGoodsList()
})
</script>

<style lang="less" scoped>
.shop-container {
    padding: 20px;
}

.shop-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
        margin: 0;
        font-size: 20px;
    }
}

.search-form {
    margin-bottom: 20px;

    .price-separator {
        margin: 0 8px;
    }
}

.goods-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.goods-item {
    transition: all 0.3s;

    &:hover {
        transform: translateY(-5px);
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
}

.goods-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.goods-info {
    padding: 14px;
}

.goods-title {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
}

.goods-price {
    margin: 8px 0;
    font-size: 18px;
    color: #f56c6c;
    font-weight: 600;
}

.goods-desc {
    margin: 8px 0;
    font-size: 14px;
    color: #606266;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.goods-actions {
    margin-top: 12px;
    display: flex;
    justify-content: space-between;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.detail-image {
    max-width: 100%;
    max-height: 300px;
    object-fit: contain;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.total-price {
    font-size: 20px;
    color: #f56c6c;
    font-weight: bold;
}
</style>
